package com.xaicode.template.batch.job.file;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.database.JdbcPagingItemReader;
import org.springframework.batch.item.database.Order;
import org.springframework.batch.item.database.support.MySqlPagingQueryProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * sql: classpath:file/test.sql
 *
 * @author beborn
 * @date 2022/1/6 0006 10:00
 */
@Component
public class DataSourceItemReaderDemo {

    @Resource
    private JobBuilderFactory jobBuilderFactory;

    @Resource
    private StepBuilderFactory stepBuilderFactory;

    @Resource
    private DataSource dataSource;

    @Bean
    public Job dataSourceItemReaderJob() throws Exception {
        return jobBuilderFactory.get("dataSourceItemReaderJob")
                .start(step())
                .build();
    }

    private Step step() throws Exception {
        return stepBuilderFactory.get("step")
                .<TransData, TransData>chunk(2)
                .reader(dataSourceItemReader())
                .writer(list -> list.forEach(System.out::println))
                .build();
    }

    private ItemReader<TransData> dataSourceItemReader() throws Exception {
        JdbcPagingItemReader<TransData> reader = new JdbcPagingItemReader<>();
        reader.setDataSource(dataSource);
        // 每次读取记录数量
        reader.setFetchSize(5);
        // 每页数量
        reader.setPageSize(5);

        MySqlPagingQueryProvider provider = new MySqlPagingQueryProvider();
        provider.setSelectClause("id,col1,col2,col3");
        provider.setFromClause("from test_job_reader");
        // 设置排序：id升序
        Map<String, Order> sort = new HashMap<>();
        sort.put("id", Order.ASCENDING);
        provider.setSortKeys(sort);
        reader.setQueryProvider(provider);

        // map to TransData
        reader.setRowMapper((resultSet, i) -> {
            TransData transData = new TransData();
            transData.setId(resultSet.getInt(1));
            transData.setCol1(resultSet.getString(2));
            transData.setCol2(resultSet.getString(3));
            transData.setCol3(resultSet.getString(4));
            return transData;
        });

        // 设置namedParameterJdbcTemplate等属性
        reader.afterPropertiesSet();
        return reader;
    }

}
